import React from "react";
import SearchHeader from "./component/SearchHeader";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import "../style/style.less";
import ThePagination from "../../../components/ThePagination";
import TheImage from '@/components/TheImage'
import QRCode from "qrcode.react";
import _ from 'lodash'
import { apiGetActivityCodeList, apiPostActivityCodeEdit } from '@/request/activityCode'

import { Button, Form, Select, Space } from "antd";
import { exportTable ,exportSheetTable} from "../../../utils/exportTable";
import logoUrl from '@/assets/images/logoIcon.png'
class List extends React.Component {
  state = {
    columns: [ 
      {
        title: "活动名称",
        dataIndex: "activityName",
        key: "activityName",
      },
      {
        title: "二维码图片",
        dataIndex: "activityCode",
        key: "activityCode",
        render: (text, record) => {
          return <div className="qrCodeBox" >
            <div className="qrCodeModal" onClick={() => { this.qrCode_downLoad(record.activityCode, record.activityName) }}>下载二维码</div>
            {/* <QRCode  id={'qrid' + record.activityCode} data-txt={record.activityName} data-code={record.activityCode} key={record.activityCode} value={record.activityCode} size={100} fgColor="#000" level="L" /> */}
            <QRCode
              id={'qrid' + record.activityCode} data-txt={record.activityName} data-code={record.activityCode} key={record.activityCode}
              // value={record.activityCode}
              value={'weixin://wxpay/bizpayurl?pr=SYSe9m1zz'}

              size={100} // 二维码的大小
              fgColor="#000000" // 二维码的颜色
              style={{ margin: 'auto' }}
              imageSettings={{ // 二维码中间的logo图片
                src: logoUrl,
                height: 40,
                width: 40,
                excavate: false, // 中间图片所在的位置是否镂空
              }}
              level="H"
            />
          </div>
        }

      },
      {
        title: "剩余次数",
        dataIndex: "residueNum",
        key: "residueNum",
      },
      {
        title: "操作",
        fixed: 'right',
        key: "doing",
        render: (text, record) => {
          return (
            <TheButton hasPermi={['activitycode:list:reset0']} onClick={() => this.goZroe(record.activityCodeId)}>次数清零</TheButton>
          )
        }
      }

    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    searchValue: {},
    loading: false,
    options: null
  };
  async componentDidMount() {
    await this.getData()

  }
  /**
   * @description 批量导出二维码到excel
   */
  exportAll() {
    let qrCodeAll = document.getElementsByTagName('canvas')
    let arr = []
    for (let index = 0; index < qrCodeAll.length; index++) {
      let name = qrCodeAll[index].getAttribute('data-txt'),
        code = qrCodeAll[index].getAttribute('data-code')
      let canvas = document.getElementById(`qrid${code}`)
      let base64 = canvas.toDataURL('image/png')
      arr.push({ name, base64 })
    }
    let th1 = [{ prop: 'name', title: '活动名称' }, { prop: 'base64', title: '二维码图片' }]
    exportSheetTable({tH_data:th1, tB_data:arr, fileName:'活动二维码',isSheet:true})
  }
  /**
   * @description 二维码下载
   * @param {string} str 后台返回的二维码字符串
   * @param {string} name 二维码对应的活动名称
   */
  qrCode_downLoad(str, name) {
    console.log(str, name);
    let canvas = document.getElementById(`qrid${str}`)
    console.log(canvas, 'canvas');
    let a = document.createElement('a')
    a.href = canvas.toDataURL('image/png')
    console.log(a.href, 'sssss');
    a.download = name || '活动二维码'
    a.click()
    setTimeout(() => {
      a.remove()
    }, 0);
  }
  goZroe = (Id) => {
    React.$confirm({
      title: "您确认对此二维码进行清零操作吗？",
      onOk: async () => {
        this.setState({ loading: true })
        let params = {
          activityCodeId: Id,
          residueNum: 0
        }
        console.log(params)
        let res = await apiPostActivityCodeEdit({ ...params })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '清零成功'
          })
          this.getData()
        }
        this.setState({ loading: false })
      },
    });
  }

  getData = async () => {
    this.setState({ loading: true })
    const { pageData, searchValue } = this.state
    let res = await apiGetActivityCodeList({ ...pageData, ...searchValue })
    // console.log(res)
    if (res.code === 0 && res.data) {
      this.setState({ dataSource: res.data, pageData: { pageNo: res.pageNo, pageSize: res.pageSize }, total: res.totalCount, loading: false })
    }
  }
  getValue = (value) => {
    // console.log(value)
    this.setState({
      searchValue: value,
      pageData: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => {
      this.getData()
    })
  }

  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  };

  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      loading,
      options
    } = this.state;
    return (
      <div className={"p-layout-box commodity-content"}>
        <SearchHeader toAdd={() => this.props.history.push('/activityCode/list/add')} exportAll={() => this.exportAll()} history={this.props.history} getValue={this.getValue} />
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns}
            dataSource={dataSource}
            loading={loading}
          />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
      </div>
    );
  }
}

export default List;
